Easy2Siksha.com
In simple words: Binary Search is like playing a guessing game where you keep halving
the possibilities until you find the answer.
What is Binary Search?
Definition: Binary Search is a searching algorithm used to find the position of a
target element in a sorted array.
It works by comparing the target element with the middle element of the array.
If the target matches the middle element, the search is successful. Otherwise, the
search continues in either the left half or the right half of the array.
Key condition: The array must be sorted (ascending or descending). Without sorting,
Binary Search cannot work correctly.
How Does Binary Search Work?
Lets break it down step by step:
1. Start with the middle element:
o Find the middle index of the array.
o Compare the target element with the middle element.
2. Check for equality:
o If the middle element equals the target, return its position.
3. If the target is smaller:
o Search only in the left half of the array.
4. If the target is larger:
o Search only in the right half of the array.
5. Repeat the process:
o Continue halving the array until the element is found or the search space
becomes empty.
Example of Binary Search
Suppose we have a sorted array: [5, 12, 23, 34, 45, 56, 67, 78, 89]
We want to search for 45.
Step 1: Middle element = 34 (index 3).
Target 45 > 34. So, search in the right half.
Step 2: New sub-array = [45, 56, 67, 78, 89].
Middle element = 67.
Target 45 < 67. So, search in the left half.
Step 3: New sub-array = [45, 56].